import { IRoute } from '@/typings';

function formatRouteTree(data: IRoute[]) {
  //{id: 2, pid: 0, path: '/course', name: 'Course', title: '课程管理'}
  //找到时是根路由
  const parents = data.filter((routeInfo) => routeInfo.pid === 0),
    //找不到时是子路由
    childrens = data.filter((routeInfo) => routeInfo.pid !== 0);

  //转为树形结构
  dataToTree(parents, childrens);

  return parents;
}

function dataToTree(parents: IRoute[], childrens: IRoute[]) {
  parents.map((parent) => {
    childrens.map((child, index) => {
      //复制一份
      let _children: IRoute[] = JSON.parse(JSON.stringify(childrens));
      //删除该项
      _children.splice(index, 1);
      //递归先删后增
      dataToTree([child], _children);

      //证明是该路由下的子路由
      if (child.pid === parent.id) {
        //该树形结构有子属性时
        if (parent.children) {
          parent.children.push(child);
        } else {
          parent.children = [child];
        }
      }
    });
  });
}

export { formatRouteTree };
